package com.ft.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import static com.alibaba.druid.util.JdbcConstants.ORACLE;

/**
 * @author mdc mdc@comit.com.cn
 * maidachao comit
 * -ft-
 */
/*@Configuration
@MapperScan(basePackages = DruidDBSecondaryConfig.PACKAGE, sqlSessionFactoryRef = "secondarySqlSessionFactory")*/
public class DruidDBSecondaryConfig {

    private Logger logger = LoggerFactory.getLogger(DruidDBSecondaryConfig.class);
    /**
     * dao层的包路径
     */
    static final String PACKAGE = "com.ft.oracle.mapper**";

    //分页，
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
    /**
     * mapper文件的相对路径
     */
    private static final String MAPPER_LOCATION = "classpath:oraclemapper/*.xml";

    @Value("${spring.datasource.secondary.url}")
    private String dbUrl;

    @Value("${spring.datasource.secondary.username}")
    private String username;

    @Value("${spring.datasource.secondary.password}")
    private String password;

    @Value("${spring.datasource.secondary.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.secondary.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.secondary.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.secondary.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.secondary.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.secondary.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.secondary.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.secondary.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.secondary.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.secondary.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.secondary.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.secondary.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.secondary.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.secondary.filters}")
    private String filters;

    @Value("{spring.datasource.secondary.connectionProperties}")
    private String connectionProperties;
    @Bean(initMethod = "init", destroyMethod = "close")
    public DataSource secondaryDataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        // configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
    @Bean(name="secondaryDataSource")
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        // configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    // 创建该数据源的事务管理
    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager secondaryTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }

    // 创建Mybatis的连接会话工厂实例
    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        //不能去掉，去掉就分页失败
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sessionFactory.setConfiguration(configuration);

        sessionFactory.setDataSource(secondaryDataSource);  // 设置数据源bean
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DruidDBSecondaryConfig.MAPPER_LOCATION));  // 设置mapper文件路径
        //添加分页功能
        sessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });
        return sessionFactory.getObject();
    }


}
